import sys
import cv2
#   rmBlackBorder: remove the black borders of one image
#   return: cropped image
def rmBlackBorder(
    src,   # input image
    thres, # threshold for cropping: sum([r,g,b] - [0,0,0](black))
    #diff,  # max tolerable difference between black borders on two side
    shrink # number of pixels to shrink after the blackBorders removed
    ):
    #   remove the black border on both right and left side

    nRow = src.shape[0]
    nCol = src.shape[1]
    left = -1
    right = nCol
    curLeft = -1
    curRight = nCol

    for j in range(0,nCol-1):
        if(sum(list(src[0,j]))<=thres and sum(list(src[nRow/2,j]))<=thres and curLeft == j-1):
            curLeft += 1
    left = curLeft

    for j in range(nCol-1,0,-1):
        if(sum(list(src[0,j]))<=thres and sum(list(src[nRow/2,j]))<=thres and curRight == j+1):
            curRight -= 1
    right = curRight

    if right-left>0 :
        print 'left margin: %d\n' %left
        print 'right margin: %d\n' %right
        src = src[0 : nRow-1, left+1 : right-1, :]
    else:
        src = src

    #
    #   remove the black border on both up and down side
    #
    nRow = src.shape[0]
    nCol = src.shape[1]
    up = -1
    down = nRow
    curUp = -1
    curDown = nRow

    for i in range(0,nRow-1):
        if(sum(list(src[i,0]))<=thres and sum(list(src[i,nCol/2]))<=thres and curUp == i-1):
            curUp += 1
    up = curUp

    for i in range(nRow-1,0,-1):
        if(sum(list(src[i,0]))<=thres and sum(list(src[i,nCol/2])) and curDown == i+1):
            curDown -= 1
    down = curDown
    # if min(up,down)>=1 and abs((up+1)-(nRow-down))<=diff and down-up>0:
        # print 'up margin: %d\n' %up
        # print 'down margin: %d\n' %down
    dst = src[up+1 : down-1-shrink, 0 : nCol-1, :]
    # else:
    #     dst = src

    return dst

if __name__ == '__main__':
    img = cv2.imread(sys.argv[1])
    #img = cv2.imread("1.jpg")
    img_out = rmBlackBorder(img, 10, 120)
    print img_out.shape
    cv2.imwrite("out.jpg", img_out)
